<template>
  <div class="updata-name">
    <van-nav-bar
      class="page-nav-bar"
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    ></van-nav-bar>
    <div class="field-wrap">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user';
export default {
  name: 'updataName',
  data() {
    return {
      localName: this.value
    };
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  methods: {
    async onConfirm() {
      this.$toast.loading({
        message: '保存中',
        duration: 0, // 持续展示
        forbidClick: true // 禁止背景点击
      });
      try {
        const localName = this.localName;
        if (!localName.length) {
          this.$toast('昵称不能为空');
          return;
        }
        await updateUserProfile({
          name: localName
        });
        this.$emit('input', localName);
        this.$emit('close');
        this.$toast.success('更改昵称成功');
      } catch (err) {
        this.$toast.fail('更新失败');
      }
    }
  }
};
</script>

<style scoped lang="less">
.updata-name {
  /deep/ .page-nav-bar {
    background-color: rgb(237, 132, 33) !important;
  }
  .field-wrap {
    padding: 20px;
  }
}
</style>
